<script setup lang='tsx'>
import type { OptionsType, PlusFormGroupRow } from 'plus-pro-components'

import router from '@/router'
import { downTpl, useGetOrgTypeDict, useMallGetAllSupplierTree } from '@fl/api/man-api/jc-authentication'
import { useEditEnterpriseContact, useEnterpriseSave, useGetCategory, useGetEnterpriseInfo } from '@fl/api/supplier'
import { SearchForm } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { cascaderValueToString } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'
import { computed, getCurrentInstance, ref } from 'vue'

import { useRule } from './use-rule'

const instance = getCurrentInstance()
const { rules } = useRule(instance)

const changeBusinessLicenseAttachmentsList = ref(false)
const changeAttachmentsAuthorizationLetterList = ref(false)

const fileType = '.rar,.zip,.doc,.docx,.pdf,.jpg,.jpeg,.png,.xlsx'
const { data: supplierTree } = useMallGetAllSupplierTree()
const initialState = {
    logo: '',
    attachmentsAuthorizationLetterList: [],
    businessLicenseAttachmentsList: [],
    businessPeriod: '', // 营业期限
    cat: [],
    enterpriseSecondType: '',
    projectPerformanceList: [], // 项目业绩
    qualificationDocumentList: [], // 资质文件
    supplyCat: [], // 供应商类别
} as any
const state = ref<any>(cloneDeep(initialState))
// 0待审核 1通过 2驳回
const isEdit = computed(() => state.value.auditStatus !== 0)

const { data: enterpriseInfoData, isLoading: isGetEnterpriseInfoLoading } = useGetEnterpriseInfo()
const { data: categoryData, isLoading: isGetCategoryLoading } = useGetCategory()
const { isPending: EnterpriseSaveLoading, mutate: EnterpriseSaveMutate } = useEnterpriseSave()
const { data: dict } = useGetOrgTypeDict()

const catJsonObj = computed(() => {
    let jsonObj = {}
    try {
        jsonObj = JSON.parse(enterpriseInfoData.value?.cat || '{}')
        return jsonObj
    }
    catch (error) {
        console.log(error)
        return jsonObj
    }
})
const catJsonStr = computed(() => {
    return JSON.stringify(state.value?.cat) ?? '[]'
})

const formRef = ref()

// #region Form
const isFormLoading = computed(() => isGetEnterpriseInfoLoading.value || isGetCategoryLoading.value)
const isSubmitLoading = computed(() => EnterpriseSaveLoading.value)
const inputMax = 50
const textareaMax = 500
const group = computed<any>(() => {
    return [
        {
            columns: [
                {
                    fieldProps: {
                        disabled: true,
                    },
                    label: '统一社会信用代码',
                    prop: 'unifiedSocialCreditCode',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '公司名称',
                    prop: 'enterpriseName',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '法定代表人',
                    prop: 'legalRepresentative',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        valueFormat: 'YYYY-MM-DD HH:mm:ss',
                        type: 'datetime',
                    },
                    label: '成立日期',
                    prop: 'establishmenDate',
                    valueType: 'date-picker',
                },
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '营业期限',
                    prop: 'businessPeriod',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '注册资本',
                    prop: 'registeredCapital',
                    valueType: 'input',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '企业LOGO',
                    prop: 'logo',

                },
                {
                    colProps: {
                        span: 24,
                    },
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: textareaMax,
                    },
                    label: '注册地址',
                    prop: 'registeredAddress',
                    valueType: 'textarea',
                },
            ],
            title: '工商信息(数据来源于企查查)',
        },
        {
            columns: [
                {
                    colProps: {
                        span: 24,
                    },
                    fieldProps: { disabled: !isEdit.value, props: { multiple: true } },
                    label: '服务类别',
                    options: categoryData as OptionsType,
                    prop: 'cat',
                    valueType: 'cascader',
                },
            ],
            title: '产品服务',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '姓名',
                    prop: 'legalRepresentative',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '电话',
                    prop: 'legalMobile',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '身份证号',
                    prop: 'legalCard',
                    valueType: 'input',
                },
            ],
            title: '法人信息',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '姓名',
                    prop: 'contactName',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '电话',
                    prop: 'contactMobile',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '身份证号',
                    prop: 'contactCardNo',
                    valueType: 'input',
                },
            ],
            title: '联系人信息',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '开户名',
                    prop: 'accountName',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '开户行',
                    prop: 'bankName',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        maxlength: inputMax,
                    },
                    label: '银行账号',
                    prop: 'accountNumber',
                    valueType: 'input',
                },
            ],
            title: '账户信息',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                    },
                    label: '供应商类型',
                    options: computed(() => {
                        if (!dict.value) {
                            return []
                        }
                        return dict.value.find((v: any) => v.value === '1')?.children ?? []
                    }),
                    prop: 'enterpriseSecondType',
                    valueType: 'select',
                    width: 120,
                },
                {
                    fieldProps: {
                        disabled: !isEdit.value,
                        props: {
                            multiple: true,
                        },
                        showAllLevels: false,
                    },
                    label: '供应商类别',
                    options: computed(() => {
                        return supplierTree.value || []
                    }),
                    prop: 'supplyCat',
                    valueType: 'cascader',
                    width: 120,
                },

            ],
            title: '机构类型',
        },
        {
            columns: [
                {
                    colProps: {
                        span: 24,
                    },
                    label: '营业执照附件',
                    prop: 'businessLicenseAttachmentsList',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '授权函',
                    prop: 'attachmentsAuthorizationLetterList',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '资质文件',
                    prop: 'qualificationDocumentList',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '项目业绩',
                    prop: 'projectPerformanceList',
                },
            ],
            title: '附件信息(仅修改企业信息上传)',
        },

    ]
})
// #endregion

// #region UI Listener
async function onSubmitBtnClick() {
    const isVal = await formRef.value.formInstance.handleSubmit()
    if (!isVal) {
        return
    }

    const target = cloneDeep(state.value)

    if ((target.enterpriseName !== enterpriseInfoData.value.enterpriseName
        || target.legalRepresentative !== enterpriseInfoData.value.legalRepresentative
        || target.registeredAddress !== enterpriseInfoData.value.registeredAddress
        || target.businessPeriod !== enterpriseInfoData.value.businessPeriod
        || target.registeredCapital !== enterpriseInfoData.value.registeredCapital) && !unref(changeBusinessLicenseAttachmentsList)) {
        ElMessage.warning('工商信息已修改,请重新上传营业执照')
        return
    }

    if ((target.contactName !== enterpriseInfoData.value.contactName
        || target.contactMobile !== enterpriseInfoData.value.contactMobile
        || target.contactCardNo !== enterpriseInfoData.value.contactCardNo) && !unref(changeAttachmentsAuthorizationLetterList)
    ) {
        ElMessage.warning('联系人信息已修改,请重新上传授权函')
        return
    }
    const businessLicenseAttachmentsList = target.businessLicenseAttachmentsList.map((v: any) => {
        return { fileName: v.name, fileUrl: v.url }
    })
    const attachmentsAuthorizationLetterList = target.attachmentsAuthorizationLetterList.map((v: any) => {
        return { fileName: v.name, fileUrl: v.url }
    })
    const qualificationDocumentList = target.qualificationDocumentList?.map((v: any) => {
        return { fileName: v.name, fileUrl: v.url }
    }) || []
    const projectPerformanceList = target.projectPerformanceList?.map((v: any) => {
        return { fileName: v.name, fileUrl: v.url }
    }) || []
    const supplyCat = JSON.stringify(target.supplyCat)
    EnterpriseSaveMutate(
        {
            ...target,
            attachmentsAuthorizationLetterList,
            businessLicenseAttachmentsList,
            cat: catJsonStr.value,
            projectPerformanceList,
            qualificationDocumentList,
            supplyCat,
        },
        {
            onSuccess: () => {
                ElMessage({ message: '操作成功', type: 'success' })
            },
        },
    )
}

function onChangeContactBtnClick() {
    router.push({ path: '/supplier-pages/enterprise-management/certification/edit' })
}
// #endregion

watchEffect(() => {
    if (enterpriseInfoData.value) {
        const businessLicenseAttachmentsList = enterpriseInfoData.value.businessLicenseAttachmentsList.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        })
        const attachmentsAuthorizationLetterList = enterpriseInfoData.value.attachmentsAuthorizationLetterList.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        })
        const qualificationDocumentList = enterpriseInfoData.value.qualificationDocumentList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const projectPerformanceList = enterpriseInfoData.value.projectPerformanceList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        state.value = cloneDeep({
            ...enterpriseInfoData.value,
            attachmentsAuthorizationLetterList,
            businessLicenseAttachmentsList,
            cat: catJsonObj.value,
            enterpriseSecondType: `${enterpriseInfoData.value.enterpriseSecondType}`,
            projectPerformanceList,
            qualificationDocumentList,
            supplyCat: enterpriseInfoData.value.supplyCat ? JSON.parse(enterpriseInfoData.value.supplyCat) : [],
            logo: enterpriseInfoData.value.logo || '',
        })
    }
    else {
        state.value = cloneDeep(initialState)
    }
})

defineExpose({
    state,
})
</script>

<template>
    <el-skeleton v-if="isFormLoading"
                 animated
    />

    <el-card v-else
             shadow="never"
    >
        <SearchForm ref="formRef"
                    v-model="state"
                    :group="group"
                    :rules="isEdit ? rules : {}"
                    submit-text="提交"
                    label-position="top"
                    :row-props="{ gutter: 20 }"
        >
            <template #group-header="{ title, icon }">
                <div>
                    <div v-if="title === '工商信息(数据来源于企查查)'"
                         class="p-5 bg-#fcf6ed leading-[32px]"
                    >
                        <div>
                            {{ state.auditStatusName }}
                        </div>

                        <div v-if="state.auditStatus === 2 && state.auditRemark">
                            驳回原因: {{ state.auditRemark }}
                        </div>
                    </div>

                    <span class="leading-[32px]">
                        {{ title }}
                        <el-icon> <component :is="icon" /> </el-icon>
                    </span>

                    <el-button v-if="false"
                               type="primary"
                               class="float-right"
                               @click="onChangeContactBtnClick"
                    >
                        变更申请
                    </el-button>
                </div>
            </template>

            <template #plus-field-logo>
                <FlUpload v-model="state.logo"
                          tips
                          accept=".jpg,.jpeg,.png"
                          :disabled="!isEdit"
                />
            </template>

            <template #plus-field-businessLicenseAttachmentsList>
                <div flex
                     flex-col
                     w-full
                >
                    <FlUpload v-model="state.businessLicenseAttachmentsList"
                              list-type="text"
                              :limit="1"
                              :file-size="10"
                              :accept="fileType"
                              :disabled="!isEdit"
                              @success="changeBusinessLicenseAttachmentsList = true"
                    />

                    <div class="text-14 c-#86909C cursor-pointer">
                        最多上传一张
                    </div>
                </div>
            </template>

            <template #plus-field-attachmentsAuthorizationLetterList>
                <div flex
                     flex-col
                     w-full
                >
                    <FlUpload v-model="state.attachmentsAuthorizationLetterList"
                              list-type="text"
                              :limit="5"
                              :file-size="10"
                              :accept="fileType"
                              tips
                              :disabled="!isEdit"
                              @success="changeAttachmentsAuthorizationLetterList = true"
                    />

                    <div class="text-14 c-#86909C cursor-pointer"
                         @click="downTpl('授权函模板')"
                    >
                        <span class="c-#EA0000">下载</span>《授权函模板》
                    </div>
                </div>
            </template>

            <template #plus-field-qualificationDocumentList>
                <FlUpload v-model="state.qualificationDocumentList"
                          list-type="text"
                          :limit="5"
                          :file-size="10"
                          :accept="fileType"
                          tips
                          :disabled="!isEdit"
                />
            </template>

            <template #plus-field-projectPerformanceList>
                <FlUpload v-model="state.projectPerformanceList"
                          list-type="text"
                          :limit="5"
                          :file-size="10"
                          :accept="fileType"
                          tips
                          :disabled="!isEdit"
                />
            </template>

            <template #footer>
                <div flex
                     justify-center
                     items-center
                >
                    <SubmitBtn v-if="isEdit"
                               type="primary"
                               :loading="isSubmitLoading"
                               @click="onSubmitBtnClick"
                    >
                        提交
                    </SubmitBtn>
                </div>
            </template>
        </SearchForm>
    </el-card>
</template>

<style lang="scss" scoped>
:deep(.logo-upload) {
    .el-upload {
        width: 100%;
    }
}

:deep(.el-card__header .leading-\[32px\]) {
    font-weight: 600;
}

:deep(.plus-form__footer) {
    justify-content: center !important;
}
</style>
